<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="65%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="企业名称" prop="companyName">
            <el-input v-model="formData.companyName" placeholder="请输入企业名称" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
            <el-input v-model="formData.unifiedSocialCreditCode" placeholder="请输入统一社会信用代码" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="委托开始时间" prop="entrustStartDate">
            <el-date-picker
              v-model="formData.entrustStartDate"
              type="month"
              value-format="YYYY-MM"
              placeholder="选择委托开始时间"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="委托结束时间" prop="entrustEndDate">
            <el-date-picker
              v-model="formData.entrustEndDate"
              type="month"
              value-format="YYYY-MM"
              placeholder="选择委托结束时间"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="月服务费(元)" prop="monthlyFee">
            <el-input v-model="formData.monthlyFee" placeholder="请输入月服务费(元)" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年份" prop="years">
            <el-date-picker
              v-model="formData.years"
              type="year"
              value-format="YYYY"
              placeholder="选择年份"
              disabled
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="formData.remarks" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="费用明细">
      <el-tabs type="border-card">
        <el-tab-pane label="明细">
            <el-button type="primary" size="small" @click="handleAddMonthFee" style="margin-bottom: 8px">新增</el-button>
              <el-table :data="monthFeeList" v-loading="monthFeeLoading" :stripe="true" :show-overflow-tooltip="true">
                <el-table-column prop="billingPeriod" label="帐期" />
                <el-table-column prop="receivingAmount" label="收款金额" />
                <el-table-column prop="receivingDate" label="收款日期" :formatter="dateFormatter2" />
                <el-table-column prop="receivingCompany" label="收款公司" />
                <el-table-column prop="paymentMethod" label="付款方式" />
                <el-table-column prop="creatorName" label="创建者" />
                <el-table-column prop="createTime" label="创建时间" :formatter="dateFormatter" />
                <el-table-column label="操作" width="98" fixed="right">
                  <template #default="scope">
                    <el-button link size="small" type="primary" @click="handleEditMonthFee(scope.row)">编辑</el-button>
                    <el-button link type="danger" size="small" @click="handleDeleteMonthFee(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            <el-pagination
              v-if="monthFeeTotal > monthFeePageSize"
              v-model:current-page="monthFeePage"
              :page-size="monthFeePageSize"
              :total="monthFeeTotal"
              layout="prev, pager, next"
              small
              style="margin-top: 8px; text-align: right;"
            />
          </el-tab-pane>
      </el-tabs>
    </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <!-- 月度费用新增/编辑弹窗 -->
    <el-dialog v-model="monthFeeDialogVisible" :title="monthFeeDialogTitle" width="500px" :close-on-click-modal="false">
      <el-form :model="monthFeeForm" label-width="110px" v-loading="monthFeeFormLoading">
        <el-form-item label="帐期" prop="billingPeriod">
          <el-input v-model="monthFeeForm.billingPeriod" placeholder="请输入帐期" />
        </el-form-item>
        <el-form-item label="收款金额" prop="receivingAmount">
          <el-input v-model="monthFeeForm.receivingAmount" placeholder="请输入收款金额" />
        </el-form-item>
        <el-form-item label="收款日期" prop="receivingDate">
          <el-date-picker v-model="monthFeeForm.receivingDate" type="date" value-format="YYYY-MM-DD" placeholder="选择收款日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="收款公司" prop="receivingCompany">
          <el-input v-model="monthFeeForm.receivingCompany" placeholder="请输入收款公司" />
        </el-form-item>
        <el-form-item label="付款方式" prop="paymentMethod">
          <el-input v-model="monthFeeForm.paymentMethod" placeholder="请输入付款方式" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="monthFeeForm.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="submitMonthFeeForm" type="primary" :disabled="monthFeeFormLoading">确 定</el-button>
        <el-button @click="monthFeeDialogVisible = false">取 消</el-button>
      </template>
    </el-dialog>
  </Dialog>
</template>
<script setup lang="ts">
import { dateFormatter, dateFormatter2} from '@/utils/formatTime'
import { AccountingCompaniesYearApi, AccountingCompaniesYearVO } from '@/api/oa/accountingcompaniesyear'
import { AccountingCompaniesMonthApi } from '@/api/oa/accountingcompaniesmonth'

/** 记账企业年度费用 表单 */
defineOptions({ name: 'AccountingCompaniesYearForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  companyName: undefined,
  entrustStartDate: undefined,
  entrustEndDate: undefined,
  unifiedSocialCreditCode: undefined,
  monthlyFee: undefined,
  years: undefined,
  remarks: undefined,
  creatorName: undefined,
  updaterName: undefined,
})
const formRules = reactive({
  companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

// 移除activeMonthTab
// const activeMonthTab = ref('1')
const monthFeeList = ref([])
const monthFeeTotal = ref(0)
const monthFeePage = ref(1)
const monthFeePageSize = ref(10)
const monthFeeLoading = ref(false)
const monthFeeDialogVisible = ref(false)
const monthFeeDialogTitle = ref('')
const monthFeeForm = ref({
  id: undefined,
  companiesYearsId: undefined,
  billingPeriod: '',
  receivingAmount: undefined,
  receivingDate: '',
  receivingCompany: '',
  paymentMethod: '',
  remarks: '',
  creatorName: '',
  createTime: '',
  updaterName: '',
  processInstanceId: ''
})
const monthFeeFormLoading = ref(false)

const arrToDateStr = (arr: number[] | undefined): string | undefined => {
  if (!arr || arr.length < 3) return undefined;
  const pad = (n: number) => n < 10 ? '0' + n : n;
  return `${arr[0]}-${pad(arr[1])}-${pad(arr[2])}`;
}
const dateStrToArr = (str: string | undefined): number[] | undefined => {
  if (!str) return undefined;
  const [y, m, d] = str.split('-').map(Number);
  return [y, m, d];
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await AccountingCompaniesYearApi.getAccountingCompaniesYear(id)
      data.entrustStartDate = arrToDateStr(data.entrustStartDate)
      data.entrustEndDate = arrToDateStr(data.entrustEndDate)
      // 修复：年份转为字符串，确保el-date-picker正确回显
      data.years = data.years ? String(data.years) : undefined
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = { ...formData.value } as any
    data.entrustStartDate = dateStrToArr(data.entrustStartDate)
    data.entrustEndDate = dateStrToArr(data.entrustEndDate)
    // 修复：年份转为数字，确保后端接收格式正确
    data.years = data.years ? Number(data.years) : undefined
    if (formType.value === 'create') {
      await AccountingCompaniesYearApi.createAccountingCompaniesYear(data)
      message.success(t('common.createSuccess'))
    } else {
      await AccountingCompaniesYearApi.updateAccountingCompaniesYear(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    companyName: undefined,
    entrustStartDate: undefined,
    entrustEndDate: undefined,
    unifiedSocialCreditCode: undefined,
    monthlyFee: undefined,
    years: undefined,
    remarks: undefined,
    creatorName: undefined,
    updaterName: undefined,
  }
  formRef.value?.resetFields()
}

// 加载所有月份的费用明细
const loadMonthFeeList = async () => {
  monthFeeLoading.value = true
  try {
    const res = await AccountingCompaniesMonthApi.getAccountingCompaniesMonthPage({
      companiesYearsId: formData.value.id, // 修正参数名
      pageNo: monthFeePage.value,
      pageSize: monthFeePageSize.value
    })
    monthFeeList.value = res.list
    monthFeeTotal.value = res.total
  } finally {
    monthFeeLoading.value = false
  }
}

// 监听分页和formData.value.id变化
watch([() => formData.value.id, monthFeePage], () => {
  if (formData.value.id) {
    monthFeePage.value = 1 // 主表单切换时重置分页
    loadMonthFeeList()
  }
})

// 新增月度费用
const handleAddMonthFee = () => {
  monthFeeDialogTitle.value = '新增月度费用'
  monthFeeForm.value = {
    id: undefined,
    companiesYearsId: formData.value.id ?? undefined, // 修正参数名
    billingPeriod: '',
    receivingAmount: undefined,
    receivingDate: '',
    receivingCompany: '',
    paymentMethod: '',
    remarks: '',
    creatorName: '',
    createTime: '',
    updaterName: '',
    processInstanceId: ''
  }
  monthFeeDialogVisible.value = true
}
// 编辑月度费用
const handleEditMonthFee = async (row: any) => {
  monthFeeDialogTitle.value = '编辑月度费用'
  monthFeeDialogVisible.value = true

  const res = await AccountingCompaniesMonthApi.getAccountingCompaniesMonth(row.id)
  res.receivingDate = arrToDateStr(res.receivingDate)
  monthFeeForm.value = res
}
// 删除月度费用
const handleDeleteMonthFee = async (row: any) => {
  await AccountingCompaniesMonthApi.deleteAccountingCompaniesMonth(row.id)
  message.success('删除成功')
  loadMonthFeeList()
}
// 提交月度费用表单
const submitMonthFeeForm = async () => {
  monthFeeFormLoading.value = true
  try {
    if (monthFeeForm.value.id) {
      await AccountingCompaniesMonthApi.updateAccountingCompaniesMonth(monthFeeForm.value)
      message.success('编辑成功')
    } else {
      await AccountingCompaniesMonthApi.createAccountingCompaniesMonth(monthFeeForm.value)
      message.success('新增成功')
    }
    monthFeeDialogVisible.value = false
    loadMonthFeeList()
  } finally {
    monthFeeFormLoading.value = false
  }
}
</script>